package com.service;
import com.entity.AsUser;
import com.entity.MethodLog;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;

@Component
@Aspect
public class LogsServiceAop
{
    @Resource
    private AsLogsService asLogsService;

    //切入点 拦截controller方法
    @Pointcut("execution( * com.controller.*.*(..) )")
    public void pointCut() { }

    //前置增强 记录用户日志
    @Before( "pointCut()" )
    public void beforeAdivce( JoinPoint jp )
    {
        //专用于记录退出操作
        String methodName = jp.getSignature().getName();
        if( "userExit".equals( methodName ) )
        {
            //首先获取HttpServletRequest
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            //获取session
            HttpSession session = request.getSession();
            //获取当前用户
            AsUser user = (AsUser) session.getAttribute( "user" );
            //获取用户不为空记录退出操作
            if( user != null )
            {
                asLogsService.addLog( user.getId() , user.getUserName() , "退出" );
            }
        }
    }

    //后置增强 记录用户日志
    @AfterReturning( pointcut = "pointCut()" )
    public void afterReturningAdivce( JoinPoint jp )
    {
        //获取执行的controller方法名
        String methodName = jp.getSignature().getName();
        //记录除退出外的其它操作
        if( !"userExit".equals( methodName ) )
        {
            //首先获取HttpServletRequest
            HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
            //获取session
            HttpSession session = request.getSession();
            //获取当前用户
            AsUser user = (AsUser) session.getAttribute( "user" );
            //获取controller对象
            Object obj = jp.getTarget();
            for( Method method : obj.getClass().getMethods() )
            {
                if( method.getName().equals( methodName ) )
                {
                    //获取自定义注解对象
                    MethodLog log = method.getAnnotation(MethodLog.class);
                    //注解不为空且不为空字符串则写入日志
                    if( log != null && !"".equals( log.operateInfo() ) )
                    {
                        //写入日志表
                        asLogsService.addLog( user.getId() , user.getUserName() , log.operateInfo() );
                    }
                }
            }
        }
    }

}
